<template>
  <v-app>
    <v-row style="position: relative;width: 100%;height: 100%;" class="pa-0 ma-0">
      <v-col class="col-md-3 d-none d-md-block pa-0 relative-full">
        <div class="login_bg relative-full">
          <div class="login_title none-select-css pa-6 pr-lg-12" style="text-align: right;color: #5f3a66">
            <h1>心之所向</h1>
            <h2> 必有回音</h2>
          </div>
          <p class="artwork-attribution">Art by <a rel="contact" href="https://www.zcool.com.cn/u/21070455">是的就是牧云</a>
          </p>
        </div>
      </v-col>
      <v-col class="col-12 col-md-9 d-flex flex-column justify-center align-center pa-0 relative-full">
        <div class="sign_up_in none-select-css">
          <p v-if="statusSignIn">还没有账户？去 <span @click="changeSignType" class="change_sign_type">注册</span> 一个吧</p>
          <p v-else>已经有一个账户了？我要去 <span @click="changeSignType" class="change_sign_type">登录</span></p>
        </div>
        <div class="sign_form_wrapper" v-if="!statusSignIn">
          <h2 style="text-align: left;color:#515151" class="mb-6">注册一个</h2>
          <v-form
            ref="signUpForm"
            class="sign_form"
          >
            <v-text-field
              v-model="name"
              :error-messages="nameErrors"
              dense
              label="登录名"
              @blur="handleSignUpNameBlur"
              required
              filled
            ></v-text-field>

            <v-text-field
              v-model="password"
              :error-messages="passwordErrors"
              dense
              label="密码"
              type="password"
              @blur="$v.password.$touch()"
              required
              filled
            ></v-text-field>

            <v-text-field
              v-model="repeatPassword"
              :error-messages="repeatPasswordErrors"
              dense
              label="重复你的密码"
              type="password"
              @blur="$v.repeatPassword.$touch()"
              required
              filled
            ></v-text-field>

            <v-checkbox
              class="mt-0"
              v-model="applyService"
              :rules="[v => !!v || '打个勾同意一下,亲']"
              label="已阅读并同意服务条款"
              required
            ></v-checkbox>

            <v-btn
              color="#ab6ab4"
              light
              class="mr-4"
              dark
              width="170px"
              @click="signUp"
            >
              注 册
            </v-btn>
          </v-form>
        </div>

        <div class="sign_form_wrapper" v-else>
          <h2 style="text-align: left;color:#515151" class="mb-6">登录</h2>
          <v-form
            ref="signInForm"
            class="sign_form"
          >
            <v-text-field
              v-model="name"
              dense
              label="登录名"
              :rules="nameRules"
              required
              filled
            ></v-text-field>

            <v-text-field
              v-model="password"
              dense
              label="密码"
              :rules="passwordRules"
              type="password"
              required
              filled
            ></v-text-field>
            <v-btn
              ref="signInBtn"
              color="#ab6ab4"
              light
              class="mt-5"
              dark
              @click="signIn"
              width="170px"
            >
              登 录
            </v-btn>
          </v-form>
        </div>
      </v-col>
    </v-row>
    <v-snackbar
      v-model="snackbar"
      :color="snackBarStyle"
      right
      :timeout="2000"
      top
    >
      {{ snackbarText }}

      <template v-slot:action="{ attrs }">
        <v-btn
          dark
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
    <v-overlay :value="signLoading" z-index="9999">
      <v-progress-circular indeterminate size="64"></v-progress-circular>
    </v-overlay>
  </v-app>
</template>

<script>
import { validationMixin } from 'vuelidate'
import { required, sameAs } from 'vuelidate/lib/validators'
import { CheckUsernameRepeat, SignIn, SignUp } from '../api/blog-api'
import cookies from '../libs/util.cookies'

export default {
  name: 'Login',

  mixins: [validationMixin],
  data: () => ({
    valid: true,
    name: '',
    password: '',
    repeatPassword: '',

    nameRules: [
      v => !!v || '请输入用户名'
    ],
    passwordRules: [
      v => !!v || '请输入密码'
    ],

    signUpNameBlur: false,

    applyService: false,
    statusSignIn: true,

    signLoading: false,
    snackbar: false,
    snackBarStyle: 'success',
    snackbarText: 'success'
  }),

  computed: {
    nameErrors () {
      const errors = []
      if (!this.$v.name.$dirty) return errors
      !this.$v.name.required && errors.push('要我叫你无名氏么?')
      // if(this.signUpNameBlur){
      //   this.signUpNameBlur =false
      !this.$v.name.isUnique && errors.push('用户名重复')
      // }
      return errors
    },

    passwordErrors () {
      const errors = []
      if (!this.$v.password.$dirty) return errors
      !this.$v.password.required && errors.push('没密码你注册个篮子')
      return errors
    },

    repeatPasswordErrors () {
      const errors = []
      if (!this.$v.repeatPassword.$dirty) return errors
      !this.$v.repeatPassword.sameAsPassword && errors.push('两次密码不一样你注册个篮子')
      return errors
    },

  },

  mounted () {
    this.enterKeyup()
  },
  beforeDestroy () {
    this.enterKeyupDestroyed()
  },

  methods: {
    showSnackBar (style, msg) {
      this.snackBarStyle = style
      this.snackbarText = msg
      this.snackbar = true
    },

    handleSignUpNameBlur (e) {
      // this.signUpNameBlur = true
      this.$v.name.$touch()
    },

    changeSignType () {
      if (this.$refs.signInForm) {
        this.$refs.signInForm.reset()
      } else {
        this.$refs.signUpForm.reset()
        this.$v.$reset()
      }
      this.$nextTick(() => {
        this.statusSignIn = !this.statusSignIn
      })
    },
    signUp () {
      this.$v.signUpGroup.$touch()
      let temp2 = this.$refs.signUpForm.validate()
      console.log(this.$v)
      if (!this.$v.signUpGroup.$invalid && temp2) {
        this.signLoading = true
        SignUp({
          userName: this.name,
          password: this.password
        }).then(res => {
          setTimeout(() => {
            this.signLoading = false
            setTimeout(() => {
              cookies.set('token', res.data.token)
              this.$router.push({ path: '/cow' })
            }, 300)
          }, 500)
        }).catch(err => {
          console.log(err)
          this.signLoading = false
        })
      }
    },
    signIn () {
      if (this.$refs.signInForm.validate()) {
        this.signLoading = true
        SignIn({
          userName: this.name,
          password: this.password
        }).then(res => {
          setTimeout(() => {
            this.signLoading = false
            cookies.set('token', res.data.token)
            localStorage.setItem('milk-user', JSON.stringify(res.data.user))
            this.$router.push({ path: '/cow/index' })
          }, 500)
        }).catch(err => {
          this.signLoading = false
        })
      }
    },
    enterKey (event) {
      const code = event.keyCode
        ? event.keyCode
        : event.which
          ? event.which
          : event.charCode
      if (code == 13) {
        this.signIn()
      }
    },
    enterKeyupDestroyed () {
      document.removeEventListener('keyup', this.enterKey)
    },
    enterKeyup () {
      document.addEventListener('keyup', this.enterKey)
    },
  },

  validations: {
    name: {
      required,
      isUnique (value) {
        // standalone validator ideally should not assume a field is required
        if (value === '' || this.statusSignIn) return true
        // simulate async call, fail for all logins with even length
        return new Promise((resolve, reject) => {
          this.nameErrorsMsg = []
          CheckUsernameRepeat({ userName: value }).then(res => {
            if (res.code === 200) {
              resolve(!res.data)
              !res.data && this.nameErrorsMsg.push('用户名重复')
              console.log('isUnique', this.$v.name)
            } else {
              resolve(false)
              this.nameErrorsMsg.push('用户名重复')
            }
          }).catch(err => {
            reject(false)
            this.nameErrorsMsg.push('用户名重复')
          })
        })
      }
    },
    password: {
      required
    },
    repeatPassword: {
      sameAsPassword: sameAs('password')
    },
    signUpGroup: ['name', 'password', 'repeatPassword']
  }
}
</script>

<style>
  .login_bg {
    position: relative;
    background: url("/pic/login_bg.jpg") no-repeat center;
    background-size: cover;
  }

  .artwork-attribution {
    font-size: 12px;
    position: absolute;
    padding-left: 20px;
    bottom: 0;
    left: 0;
    right: 0;
  }

  .sign_form_wrapper {
    width: 500px;
  }

  @media (max-width: 600px) {
    .sign_form_wrapper {
      width: 90%;
    }
  }

  .sign_form > div {
    margin-bottom: 6px !important;
  }

  .sign_up_in {
    position: absolute;
    font-size: 12px;
    text-align: right;
    padding-top: 4px;
    padding-right: 12px;
    height: 30px;
    top: 0;
    left: 0;
    right: 0;
  }

  .change_sign_type {
    cursor: pointer;
    font-weight: bold;
    color: #ab6ab4;
  }
</style>
